'''
Created on Mar 10, 2010

@author: sternron



'''
import dot_parser
import graph
import logging
import sys
import cliques.randomCliqueSearch
import orchid
import re
from cliques.randomCliqueSearch import randomCliqueSearch
from cliques.knownDegreeSearch import knownDegreeSearch
from cliques.cliqueStarSearch import cliqueStarSearch
from cliques.cliqueSearchLowerbound import CliqueSearchLowerbound
from cliques.mdp.mdpBasedSearch import mdpBasedSearch
from cliques.mdp.limitedSampling import LimitedSampling
from cliques.closest.closestCliqueSearch import ClosestCliqueSearch

import timerManager
import os
import urllib2
import time
import random
#import urllib2.HTTPError
import onlineCliqueSearch
from cliques.closest.ongoingCliqueSearch import OngoingCliqueSearch
from cliques.closest.ongoingBreadthFirstSearch import OngoingBreadthFirstSearch
from webgraphs.onlineOngoingCliqueSearch import OnlineOngoingCliqueSearch

RESOURCE_RESULTS_DIR = "../resources/results"
RESOURCE_NANOTOXIC_DIR = "../resources/nanotoxic"
RESOURCE_ROOT_PAPERS_FILE = "%s/papersOver3.txt" % RESOURCE_NANOTOXIC_DIR
RESOURCE_ROOT_NODES_FILE = "%s/SourceNodes40.txt" % RESOURCE_RESULTS_DIR
RESOURCE_ROOT_CKG_FILE = "%s/SourceNodes40.dot" % RESOURCE_RESULTS_DIR
RESOURCE_ROOT_EXPLORED_FILE = "%s/ExploredNodes40.txt" % RESOURCE_RESULTS_DIR
RESOURCE_CONFIG_FILE = "%s/online.config.txt" % RESOURCE_RESULTS_DIR

class OnlineRunner(object):
    ''' An online experiment runner '''
    def __init__(self):
        print "Nothing yet"
        
    def load_old_results(self, result_file_name):        
        ''' Load the previous results file into a configuration list'''
        old_configurations=[]
        in_file = open(result_file_name, 'r')
        header_line = True
        for line in in_file:
            if header_line:
                header_line = False
            else:
                line = line.strip()
                line_parts = line.split("\t")
                root = line_parts[0].strip()
                k = int(line_parts[1].strip())
                iteration = int(line_parts[2].strip())
                algorithm = line_parts[3].strip()
                configuration = (root, k, iteration, algorithm)
                old_configurations.append(configuration)
        in_file.close()
        return old_configurations

    def continue_search(self,pConfig_file_name,pExploration_limit,pSearcher):
        ''' Search for a k-clique starting from a partial exploration of the unknown graph '''
        pSearcher.import_state(pConfig_file_name)
                                    
        try:                            
            pSearcher.timer_manager.create_timer('total_runtime')
            logging.info("Starting %d-clique search with %s !!" % (pSearcher.algorithm.k, pSearcher.algorithm))
            pSearcher.search(pExploration_limit)                                       
            first_configuration=False
        except urllib2.HTTPError, error:
            logging.exception(error)
            logging.error(error.read())
            logging.info("Total CKG nodes: %d" % len(pSearcher.ckg.nodes()))
            logging.info("Exporting state...")
            pSearcher.export_state(pConfig_file_name)
            logging.info("State exported!")
            out_file.close()
            sys.exit()
            
        logging.info("Exporting state...")
        pSearcher.export_state(pConfig_file_name)
        logging.info("State exported!")
      
    
def main(): 
    logging.basicConfig(level=logging.DEBUG)
    logging.root.addHandler(logging.StreamHandler(sys.stdout))
    online_experiment_runner = OnlineRunner()
    clique_algorithm = OngoingCliqueSearch()
    #clique_algorithm = OngoingBreadthFirstSearch()
    searcher = OnlineOngoingCliqueSearch(clique_algorithm)
    searcher.set_required_members(140)
    exploration_limit = 1000

    online_experiment_runner.continue_search(RESOURCE_CONFIG_FILE,exploration_limit, searcher)



    
if __name__ == '__main__':
    main()